import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API2, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    if (!config.headers.Authorization && store.state.user.token) {
      // 在请求拦截器中的请求头上设置token
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(res)
    if (!res.isSuccess) {
      Message({
        message: res.msg || 'Error!',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default request
